// 面板数据
let panelData = {
    character: {},
    backpack: {},
    rank: {},
    card: {}
};

// 控制面板显示和隐藏
class PanelController {
    constructor() {
        this.currentPanel = null;
        this.init();
    }

    init() {
        // 绑定左上角控制按钮事件
        document.getElementById('btnCharacter')?.addEventListener('click', () => {
            this.showPanel('characterPanel', {
                name: '玩家',
                level: 50,
                hp: 850,
                hpMax: 1000,
                exp: 4500
            });
        });

        document.getElementById('btnBackpack')?.addEventListener('click', () => {
            this.showPanel('backpackPanel', {
                items: [
                    { name: '药水1' }, { name: '装备1' }, { name: '卡片1' },
                    { name: '药水2' }, { name: '装备2' }, { name: '卡片2' }
                ]
            });
        });

        document.getElementById('btnRank')?.addEventListener('click', () => {
            this.showPanel('rankPanel', {
                ranks: [
                    { name: '第一名', level: 100, score: 10000 },
                    { name: '第二名', level: 95, score: 9500 },
                    { name: '第三名', level: 90, score: 9000 }
                ]
            });
        });

        document.getElementById('btnCard')?.addEventListener('click', () => {
            this.showPanel('cardPanel', {
                cardTitle: '获得新卡片！',
                cardName: '传奇剑客',
                description: '这是一张非常稀有的传奇卡牌',
                attack: 999,
                defense: 888
            });
        });

        // 绑定关闭按钮事件
        document.getElementById('closeCharacter')?.addEventListener('click', () => {
            this.hidePanel('characterPanel');
        });

        document.getElementById('closeBackpack')?.addEventListener('click', () => {
            this.hidePanel('backpackPanel');
        });

        document.getElementById('closeRank')?.addEventListener('click', () => {
            this.hidePanel('rankPanel');
        });

        document.getElementById('closeCard')?.addEventListener('click', () => {
            this.hidePanel('cardPanel');
        });

        // ESC键关闭面板
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape' && this.currentPanel) {
                this.hidePanel(this.currentPanel);
            }
        });
    }

    /**
     * 显示面板（支持传入数据）
     * @param {string} panelId 面板ID
     * @param {object} data 面板数据
     */
    showPanel(panelId, data = null) {
        // 如果是同一个面板，不重复打开
        if (this.currentPanel === panelId) {
            return;
        }

        // 先关闭当前面板
        if (this.currentPanel) {
            const currentPanelEl = document.getElementById(this.currentPanel);
            if (currentPanelEl) {
                currentPanelEl.classList.remove('show');
            }
            this.currentPanel = null;
        }

        // 添加暗色蒙版
        let overlay = document.querySelector('.overlay-dark');
        if (!overlay) {
            overlay = document.createElement('div');
            overlay.className = 'overlay-dark';
            document.body.appendChild(overlay);
        }
        overlay.classList.add('show');

        // 如果传入数据，更新面板
        if (data) {
            this.updatePanelData(panelId, data);
        }

        // 显示新面板
        const panel = document.getElementById(panelId);
        if (panel) {
            setTimeout(() => {
                panel.classList.add('show');
                this.currentPanel = panelId;
            }, 50);

            // 点击蒙版关闭面板
            overlay.addEventListener('click', this.closePanelHandler = () => {
                this.hidePanel(panelId);
            });
        }
    }

    /**
     * 隐藏面板
     * @param {string} panelId 面板ID
     */
    hidePanel(panelId) {
        const panel = document.getElementById(panelId);
        if (panel) {
            panel.classList.remove('show');
            this.currentPanel = null;

            // 移除暗色蒙版
            const overlay = document.querySelector('.overlay-dark');
            if (overlay) {
                overlay.classList.remove('show');
                if (this.closePanelHandler) {
                    overlay.removeEventListener('click', this.closePanelHandler);
                }
            }

            // 通知Android面板已关闭
            if (window.Android) {
                window.Android.sendToAndroid('panel_closed', JSON.stringify({
                    panelId: panelId
                }));
            }
        }
    }

    /**
     * 更新面板数据
     */
    updatePanelData(panelId, data) {
        if (panelId === 'characterPanel') {
            this.updateCharacterPanel(data);
        } else if (panelId === 'backpackPanel') {
            this.updateBackpackPanel(data);
        } else if (panelId === 'rankPanel') {
            this.updateRankPanel(data);
        } else if (panelId === 'cardPanel') {
            this.updateCardPanel(data);
        }
    }

    /**
     * 更新角色信息面板
     */
    updateCharacterPanel(data) {
        // 更新角色基本信息
        document.querySelector('.character-name').textContent = data.name || '玩家';
        document.querySelector('.character-level').textContent = `等级: ${data.level || 1}`;
        
        // 更新生命值
        const hpMax = data.hpMax || 1000;
        const hpCurrent = data.hp || hpMax;
        const hpPercent = (hpCurrent / hpMax * 100).toFixed(0);
        document.querySelector('.stat-item .stat-bar .stat-fill').style.width = hpPercent + '%';
        document.querySelector('.stat-item .stat-value').textContent = `${hpCurrent}/${hpMax}`;
    }

    /**
     * 更新背包面板
     */
    updateBackpackPanel(data) {
        const items = data.items || [];
        const grid = document.querySelector('.backpack-grid');
        if (grid) {
            grid.innerHTML = '';
            items.forEach(item => {
                const slot = document.createElement('div');
                slot.className = 'item-slot';
                slot.textContent = item.name || '物品';
                grid.appendChild(slot);
            });
        }
    }

    /**
     * 更新排行榜面板
     */
    updateRankPanel(data) {
        const ranks = data.ranks || [];
        const rankList = document.querySelector('.rank-list');
        if (rankList) {
            rankList.innerHTML = '';
            ranks.forEach((player, index) => {
                const rankItem = document.createElement('div');
                rankItem.className = `rank-item ${index === 0 ? 'gold' : index === 1 ? 'silver' : index === 2 ? 'bronze' : ''}`;
                rankItem.innerHTML = `
                    <div class="rank-number">${index + 1}</div>
                    <div class="rank-avatar">👤</div>
                    <div class="rank-info">
                        <div class="rank-name">${player.name}</div>
                        <div class="rank-level">等级: ${player.level}</div>
                    </div>
                    <div class="rank-score">${player.score}</div>
                `;
                rankList.appendChild(rankItem);
            });
        }
    }

    /**
     * 更新卡片特效面板
     */
    updateCardPanel(data) {
        document.querySelector('.card-title').textContent = data.cardTitle || '获得新卡片！';
        document.querySelector('.card-name').textContent = data.cardName || '传奇卡牌';
        document.querySelector('.card-description').textContent = data.description || '这是一张非常稀有的传奇卡牌。';
    }
}

// 创建全局控制器实例
let controller;

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    controller = new PanelController();
    console.log('RPG游戏上层界面已加载');

    // 注册全局函数供Android调用
    window.showPanel = function(panelType, data) {
        if (!controller) return;
        
        let panelId = '';
        switch(panelType) {
            case 'character':
                panelId = 'characterPanel';
                break;
            case 'backpack':
                panelId = 'backpackPanel';
                break;
            case 'rank':
                panelId = 'rankPanel';
                break;
            case 'card':
                panelId = 'cardPanel';
                break;
            default:
                console.warn('未知的面板类型:', panelType);
                return;
        }
        
        controller.showPanel(panelId, data);
    };
    
    window.hidePanel = function(panelType) {
        if (!controller) return;
        
        let panelId = '';
        switch(panelType) {
            case 'character':
                panelId = 'characterPanel';
                break;
            case 'backpack':
                panelId = 'backpackPanel';
                break;
            case 'rank':
                panelId = 'rankPanel';
                break;
            case 'card':
                panelId = 'cardPanel';
                break;
            default:
                console.warn('未知的面板类型:', panelType);
                return;
        }
        
        controller.hidePanel(panelId);
    };
    
    console.log('全局面板控制函数已注册');
});
